package com.sj.security;

import cn.hutool.json.JSONUtil;
import com.sj.common.lang.ApiResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2022-03-10
 * Time: 下午 13:18
 * Description: 登陆失败处理器
 *
 * @author xiaoqi
 * @since 2022-03-10
 */
@Component
public class LoginFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        // 如果异常是错误账户密码 自己处理异常信息
        if (e instanceof BadCredentialsException) {
            outputStream.write(JSONUtil.toJsonStr(ApiResult.error("密码错误")).getBytes("UTF-8"));
        } else {
            // 如果是其他错误信息，比如验证码错误，直接打印 捕获的异常信息
            outputStream.write(JSONUtil.toJsonStr(ApiResult.error(e.getMessage())).getBytes("UTF-8"));
        }
        outputStream.flush();
        outputStream.close();
    }
}